﻿using Elasticsearch.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Nest;
using XYS.Core.Models;
using XYS.Service.Core.Util.Helper;

namespace XYS.Service.Core
{
    /// <summary>
    /// Elastic 配置
    /// 注入ElasticClient
    /// https://github.com/elastic/elasticsearch-net
    /// </summary>
    public static class ElasticExtension
    {
        /// <summary>
        /// Elastic 配置
        /// 注入ElasticClient
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static WebApplicationBuilder AddElastic(this WebApplicationBuilder builder, ILogger logger)
        {
            //获取 配置 ElasticSearchSetting
            var elasticSettings = builder.Configuration.GetSection("ElasticSettings").Get<List<ElasticSearchSetting>>();
            if (elasticSettings != null && elasticSettings.Count > 0)
            {
                logger.LogInformation($"读取到Elastic配置，开始加载配置");
                foreach (var elasticSetting in elasticSettings)
                {
                    if (!string.IsNullOrWhiteSpace(elasticSetting.ElasticName))
                    {
                        if (string.IsNullOrWhiteSpace(elasticSetting.ElasticSearchHost))
                        {
                            logger.LogWarning($"未加载[{elasticSetting.ElasticName}]配置.因为您未配置 ElasticSearchHost");
                            continue;
                        }
                        logger.LogInformation($"已加载[{elasticSetting.ElasticName}]配置");

                        var settings = new ConnectionSettings(new SingleNodeConnectionPool(new Uri(elasticSetting.ElasticSearchHost)))
                            .EnableDebugMode() // 启用调试模式
                            .PrettyJson();     // 使 JSON 输出更易读
                        //创建 ElasticClient 
                        ElasticClientHelper.ElasticClients[elasticSetting.ElasticName] = new ElasticClient(settings.EnableTcpKeepAlive(elasticSetting.KeepAliveTime, elasticSetting.keepAliveInterval).MaximumRetries(5));
                    }
                }
                logger.LogInformation($"读取到Elastic配置完成");
            }
            return builder;
        }


    }
}
